﻿Public Class frmStats
    Private Sub frmStats_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveWindowPos(REGAPP, Me)
        StatsForm = Nothing
    End Sub

    Private Sub frmStats_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            GetWindowPos(REGAPP, Me)
            Refresh()
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Friend Overloads Sub Refresh()
        Dim NumSeries As Integer = 0, Count As Integer = 0, NonCalc As Integer = 0, NonDet As Integer = 0, Exceed As Integer = 0
        Dim MinDate As Date = Date.MaxValue, MaxDate As Date = Date.MinValue
        Dim MinValue = Double.MaxValue, MaxValue As Double = Double.MinValue
        Dim MeanValue As Double = 0
        Dim CurrentCount As Integer = 0

        With tvStats
            .Nodes.Clear()
            For Each ser As clsSeries In ActiveGraphTab.Series
                Dim NodeText As String = ser.Label
                If ser.Table IsNot Nothing AndAlso ser.Table.TableType = clsTable.enumTableType.Calibration Then NodeText = ser.Table.Calibration.Name
                With .Nodes.Add(NodeText)
                    For Each s As String In StringSplit(ser.StatsText, "\n")
                        .Nodes.Add(s)
                        'tim wool wants summary stats for all series; to avoid having to carry individual stats around, parse the stats string and recompute
                        Dim ar() As String = s.Split(":")
                        If ar.Length >= 2 Then
                            Select Case ar(0)
                                Case "Count" : Count += ar(1) : CurrentCount = ar(1) : NumSeries += 1
                                Case "Non-Calc" : NonCalc += ar(1)
                                Case "Non-Det" : NonDet += ar(1)
                                Case "Exceed" : Exceed += Val(ar(1))
                                Case "Min Date"
                                    Dim dt As Date = CDate(ar(1) & ":" & ar(2))
                                    If dt < MinDate Then MinDate = dt
                                Case "Max Date"
                                    Dim dt As Date = CDate(ar(1) & ":" & ar(2))
                                    If dt > MaxDate Then MaxDate = dt
                                Case "Min Value" : MinValue = Math.Min(MinValue, Val(ar(1)))
                                Case "Max Value" : MaxValue = Math.Max(MaxValue, Val(ar(1)))
                                Case "Mean Value" : MeanValue += ar(1) * CurrentCount
                            End Select
                        End If
                    Next
                End With
            Next
            If NumSeries > 1 Then
                With .Nodes.Add("Summary for All Series")
                    Dim Stats As String = String.Format("Num Series: {0}\nCount: {1}\nNon-Calc: {2}\nNon-Det: {3}\nExceed: {4} ({10:N1}%)\nMin Date: {5}\nMax Date: {6}\n" &
                                                        IIf(MinValue = Double.MaxValue, "", "Min Value: {7:N3}\nMax Value: {8:N3}\n") &
                                                        "Mean Value: {9:N3}",
                                                        NumSeries, Count, NonCalc, NonDet, Exceed, MinDate.ToString(MyDateFormat), MaxDate.ToString(MyDateFormat),
                                                        MinValue, MaxValue, MeanValue / Count, Exceed * 100.0 / Math.Max(Count, 1))
                    For Each s As String In StringSplit(Stats, "\n")
                        .Nodes.Add(s)
                    Next
                End With
            End If
            .ExpandAll()
        End With
    End Sub

    Private Sub mnuStatsClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuCollapse.Click, mnuExpand.Click, mnuCopy.Click, mnuNotes.Click, tbCollapse.Click, tbExpand.Click, tbNotes.Click, tbCopy.Click, mnuFormat.Click, tbFormat.Click
        With tvStats
            If sender Is mnuExpand Or sender Is tbExpand Then
                .ExpandAll()
            ElseIf sender Is mnuCollapse Or sender Is tbCollapse Then
                .CollapseAll()
            ElseIf sender Is mnuCopy Or sender Is tbCopy Then
                Dim s As String = ""
                For Each n As TreeNode In .Nodes
                    AddNodes(s, n, True)
                    s &= "\n\n"
                Next
                Clipboard.Clear()
                Clipboard.SetText(s.Replace("\n", vbCrLf).Replace("\t", vbTab))
            ElseIf sender Is mnuNotes Or sender Is tbNotes Then
                Dim s As String = ""
                For Each n As TreeNode In .Nodes
                    If n.IsSelected Then
                        AddNodes(s, n, False)
                        's &= "\n\n"
                    End If
                Next
                If s = "" Then
                    WarningMsg("Please select a major node to identify the statistics to place on the graph note.")
                Else
                    'hide all series statistics & graph notes
                    For i As Integer = 0 To ActiveGraphTab.Series.Count - 1
                        ActiveGraphTab.Series(i).StatsVisible = False
                    Next
                    With ActiveGraphTab.GraphOptions
                        .NoteText = ""
                        .NoteVisible = False
                    End With

                    If .SelectedNode.Text = "Summary for All Series" Then 'place as graph notes
                        With ActiveGraphTab.GraphOptions
                            .NoteText = s '.Replace("\n", vbCrLf).Replace("\t", "")
                            .NoteAlignment = enumNoteAlignment.Center
                            .NoteVisible = True
                        End With
                    Else 'turn on series stats display
                        For i As Integer = 0 To ActiveGraphTab.Series.Count - 1
                            If .Nodes(i).IsSelected Then
                                ActiveGraphTab.Series(i).StatsVisible = True
                                Exit For
                            End If
                        Next
                    End If
                End If
            ElseIf sender Is mnuFormat Or sender Is tbFormat Then
                With New frmOptions
                    .TabControl1.SelectedIndex = 1
                    .ShowDialog(Me)
                    .Dispose()
                End With
            End If
        End With
    End Sub

    Private Sub AddNodes(ByRef s As String, ByVal node As TreeNode, ByVal IncludeTopNodeName As Boolean)
        Static level As Integer = 0
        For i As Integer = 0 To level - 1
            s &= "\t"
        Next
        If IncludeTopNodeName Or level <> 0 Then s &= node.Text & "\n"
        level += 1
        For Each n As TreeNode In node.Nodes
            AddNodes(s, n, IncludeTopNodeName)
        Next
        level -= 1
    End Sub

End Class